import md5
import urllib
import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.ext import db
from Img import Img

class lookimg(webapp.RequestHandler):
    def get(self):
        #if If-Modified-Since header present, we just send 304 status code
        if self.request.headers.has_key('If-Modified-Since'):
            self.response.set_status(304)
            return
        #get the imgId
        imgId = self.request.path_qs[len('/look/'):]
        #fetch img from db
        imgs = Img.all().filter('imgId = ', imgId).fetch(1)
        if len(imgs) > 0:
            #image exists, we send to client
            img = imgs[0]
            self.response.headers['Content-Length'] = str(img.contentLength)
            self.response.headers['Content-Type'] = str(img.contentType)
            self.response.headers['Last-Modified'] = img.date.strftime("%a, %d %b %Y %H:%M:%S GMT")
            self.response.out.write(img.content)
            #and add accessTimes by 1 if not access by uploader
            user = users.get_current_user()
            if not user or str(user.email()) != str(img.uploader.email()):
                img.accessTimes = img.accessTimes + 1
                img.put()
            return
        else:
            #image does not exists, we show error
            self.redirect('/error/' + 'There is no image with id [' + imgId + ']')
            return
    
def main():
    application = webapp.WSGIApplication(
                           [('/look/.*', lookimg)],
                           debug=True)
    wsgiref.handlers.CGIHandler().run(application)

if __name__ == '__main__':
    main()

